
Component({
  /**
   * 组件的属性列表
   */
  properties: {
    waterFall: Array
  },

  /**
   * 组件的初始数据
   */
  data: {
    imgList: [],
    leftList: [],
    rightList: [],
    leftHeight: 0,
    rightHeight: 0
  },

  observers: {
    'waterFall': function(data) {
      if(data.length !== 0) {
        this.setData({
          imgList: data
        })
        this._pushData(this.data.imgList)
      }
    }
  },

  lifetimes: {
    attached () {
      // await this._getListHeight();
    },
    ready() {
    }
  },

  pageLifetimes: {
    resize(size) {
      console.log(size);
    }
  },

  /**
   * 组件的方法列表
   */
  methods: {
    _getListHeight(left, right) {
      let height = {}
      // exec回调函数为异步，返回promise对象
      return new Promise((resolve, reject) => {
        const query = this.createSelectorQuery().in(this)
        query.select('#left').boundingClientRect()
        query.select('#right').boundingClientRect()
        this.setData(
          {
            leftList: left, 
            rightList: right
          }, () => {
          query.exec(res => {
            height.left = res[0].height
            height.right = res[1].height
            resolve(height)
          })
        })
      })
    },

    async _pushData(list) {
      let left = this.data.leftList
      let right = this.data.rightList
      // 解决不能等待上次数据渲染后获取元素高度的问题
      for(const item of list) {
        this.data.leftHeight <= this.data.rightHeight ? left.push(item) : right.push(item)
        let res = await this._getListHeight(left, right)
        this.setData({
          leftHeight: res.left,
          rightHeight: res.right
        })
      }
    }
  }
})
